import Konva from "konva"
import { componentsShapeType } from './consts'
export class KonvaJs {
    // 构造函数
    constructor(id) {
        // 将传入的id赋值给实例的id属性
        this.id = id;
        this.SCALE_BY = 1.1;
        this.stage = null;
        this.layers = []; // 存储所有图层
        this.currentLayer = null;
        this.tr = this.newTransformer();
        this.text = this.newText();
        this.group = this.newGroup({ x: 0, y: 0 });
        this.transformer = null;
        this.init();
    }
    // 初始化函数
    init() {
        // 获取id为this.id的元素
        const el = document.getElementById(this.id)
        // 如果元素不存在，则返回
        if (!el) {
            return
        }
        
        // 确保DOM元素有明确的尺寸
        el.style.width = '100%';
        el.style.height = '100%';
        
        // 获取元素的宽度和高度
        const { clientWidth, clientHeight } = el
        
        // 创建一个新的舞台
        this.stage = this.newStage({
            container: this.id,
            width: clientWidth,
            height: clientHeight,
            draggable: false,
        })
        
        // 创建第一个图层
        this.currentLayer = this.newLayer();
        this.layers.push(this.currentLayer);
        this.stage.add(this.currentLayer);
        
        // 创建并配置组
        this.group = this.newGroup({
            x: 0,
            y: 0,
            width: clientWidth,
            height: clientHeight
        });
        
        this.currentLayer.add(this.group);
        
        // 绘制棋盘
        this.drawBoard();

        // 创建变换器
        this.transformer = new Konva.Transformer({
            rotateEnabled: true,
            borderStroke: '#409eff',
            borderWidth: 1,
            anchorStroke: '#409eff',
            anchorFill: '#409eff',
            anchorSize: 8,
            anchorCornerRadius: 4,
            keepRatio: false,
        });

        // 将变换器添加到当前层
        this.currentLayer.add(this.transformer);
        // 确保变换器在最上层
        this.transformer.moveToTop();

        // 监听舞台点击事件
        this.stage.on('click tap', (e) => {
            // 如果点击的是舞台空白处，隐藏变换器
            if (e.target === this.stage) {
                this.transformer.nodes([]);
                this.currentLayer.draw();
                return;
            }

            // 如果点击的是形状，显示变换器
            if (e.target.getType() !== 'Transformer') {
                this.transformer.nodes([e.target]);
                this.currentLayer.draw();
            }
        });
    }
    // 绘制棋盘
    drawBoard() {
        if (!this.stage || !this.currentLayer) {
            return;
        }
        
        const width = 700;
        const height = 700;
        const x = (this.stage.width() - width) / 2;
        const y = (this.stage.height() - height) / 2;
        
        // 创建棋盘
        const board = this.newRect({
            x: x,
            y: y,
            width: width,
            height: height,
            fill: '#ffffff',
            stroke: '#dcdfe6',
            strokeWidth: 1,
            cornerRadius: 0,
            shadowColor: 'black',
            shadowBlur: 10,
            shadowOpacity: 0.2,
            shadowOffset: { x: 5, y: 5 },
            listening: false // 禁用事件监听，防止遮挡其他元素
        });
        
        this.group.add(board);
        this.currentLayer.batchDraw();
    }

    // 监听窗口大小变化
    onresize() {
        // 获取当前元素的id
        const el = document.getElementById(this.id)
        // 如果没有获取到元素，则返回
        if (!el) return
        // 获取当前元素的宽度和高度
        const { clientWidth, clientHeight } = el
        // 设置舞台的宽度和高度
        this.stage.setAttrs({
            width: clientWidth,
            height: clientHeight,
        })
        this.stage.draw();
    }

    // addListenerStageEvents() {
    //     if (!this.stage) return
    //     this.stage.on('wheel', (e) => {
    //         if (!this.stage) return
    //         const oldScale = this.stage.scaleX()
    //         const pointer = this.stage.getPointerPosition()
    //         const mousePointTo = {
    //             x: (pointer.x - this.stage.x()) / oldScale,
    //             y: (pointer.y - this.stage.y()) / oldScale,
    //         }
    //         let directtion = e.evt.deltaY > 0 ? -1 : 1
    //         if (e.evt.ctrlKey) {
    //             directtion = -directtion
    //         }
    //         const newScale = directtion > 0 ? oldScale * this.SCALE_BY : oldScale / this.SCALE_BY
    //         this.stage.scale({ x: newScale, y: newScale })
    //         const newPos = {
    //             x: pointer.x - mousePointTo.x * newScale,
    //             y: pointer.y - mousePointTo.y * newScale,
    //         }
    //         this.stage.position(newPos)
    //     })
    // }

    // 绘制图形
    drawShapes(type, position, test) {
        if (!this.stage || !this.currentLayer) return;
        
        let shapes;
        const id = this.getUUID();
        
        if (type === componentsShapeType.RECT) {
            const rectShapes = this.stage.find('.rect');
            shapes = this.newRect({
                id: id,
                title: `矩形${rectShapes.length + 1}`,
                name: 'rect',
                width: 200,
                height: 100,
                fill: '#fff',
                stroke: 'blck',
                strokeWidth: 1,
                type: type,
                draggable: true,
                create: true,
                scaleX: 1,
                scaleY: 1,
                opacity: 1,
            });
        } else if (type === componentsShapeType.TEXT) {
            shapes = this.newText({
                id: id,
                title: `双击编辑标题`,
                name: 'text',
                text: '双击编辑标题',
                fontSize: 20,
                draggable: true,
                create: true,
                type: type,
            });
            this.tr.nodes([shapes]);
        } else if (type === componentsShapeType.IMAGE) {
            shapes = this.newImage({
                id: id,
                title: `图片`,
                name: 'image',
                draggable: true,
                create: true,
                type: type,
                width: 200,
                height: 100,
                opacity: 1,
                scaleX: 1,
                scaleY: 1,
                ...test
            });
        }
        
        if (!shapes) return;
        shapes.position(position);
        this.group.add(shapes);
        this.currentLayer.batchDraw();
        return shapes;
    }

    // 获取UUID
    getUUID() {
        // 获取当前时间
        let d = Date.now()
        // 如果浏览器支持performance.now()方法，则将当前时间加上performance.now()的返回值
        if (typeof performance !== 'undefined' && typeof performance.now === 'function') {
            d += performance.now()
        }
        // 返回一个UUID
        return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
            // 生成一个随机数
            const r = (d + Math.random() * 16) % 16 | 0
            // 将当前时间除以16
            d = Math.floor(d / 16)
            // 如果c为x，则返回r，否则返回r与0x3按位与的结果与0x8按位或的结果
            return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16)
        })
    }

    // 创建一个新的Konva.Stage对象
    newStage(data) {
        // 返回一个新的Konva.Stage对象
        return new Konva.Stage(data)
    }
    newLayer(data) {
        return new Konva.Layer(data)
    }
    newTransformer(data) {
        return new Konva.Transformer(data)
    }
    newGroup(data) {
        return new Konva.Group(data)
    }
    newRect(data) {
        return new Konva.Rect(data)
    }
    newCircle(data) {
        return new Konva.Circle(data)
    }
    newText(data) {
        return new Konva.Text(data)
    }
    newImage(data) {
        console.log(data);
        
        return new Konva.Image(data)
    }
    newRegularPolygon(data) {
        return new Konva.RegularPolygon(data)
    }
    newLine(data) {
        return new Konva.Line(data)
    }
    newLabel(data) {
        return new Konva.Label(data)
    }
    newTag(data) {
        return new Konva.Tag(data)
    }
    newArrows(data) {
        return new Konva.Arrow(data)
    }
    newPath(data) {
        return new Konva.Path(data)
    }

    // 添加新图层
    addLayer(y = 0) {
        const layer = this.newLayer();
        layer.y(y);
        
        // 为每个图层创建独立的组
        const group = this.newGroup({
            x: 0,
            y: 0,
            width: this.stage.width(),
            height: this.stage.height()
        });
        
        layer.add(group);
        this.layers.push(layer);
        this.stage.add(layer);
        this.currentLayer = layer;
        this.group = group; // 更新当前组
        
        // 绘制棋盘
        this.drawBoard();
        
        return layer;
    }

    addShape(type, x, y) {
        if (!this.layers.length) return;

        const layer = this.layers[this.layers.length - 1];
        let shape;

        switch (type) {
            case 'rect':
                shape = new Konva.Rect({
                    x: x,
                    y: y,
                    width: 100,
                    height: 100,
                    stroke: '#000000',
                    strokeWidth: 2,
                    draggable: true
                });
                break;
            case 'circle':
                shape = new Konva.Circle({
                    x: x,
                    y: y,
                    radius: 50,
                    stroke: '#000000',
                    strokeWidth: 2,
                    draggable: true
                });
                break;
            case 'triangle':
                shape = new Konva.RegularPolygon({
                    x: x,
                    y: y,
                    sides: 3,
                    radius: 50,
                    stroke: '#000000',
                    strokeWidth: 2,
                    draggable: true
                });
                break;
            case 'pentagon':
                shape = new Konva.RegularPolygon({
                    x: x,
                    y: y,
                    sides: 5,
                    radius: 50,
                    stroke: '#000000',
                    strokeWidth: 2,
                    draggable: true
                });
                break;
            case 'hexagon':
                shape = new Konva.RegularPolygon({
                    x: x,
                    y: y,
                    sides: 6,
                    radius: 50,
                    stroke: '#000000',
                    strokeWidth: 2,
                    draggable: true
                });
                break;
            case 'star':
                shape = new Konva.Star({
                    x: x,
                    y: y,
                    numPoints: 5,
                    innerRadius: 30,
                    outerRadius: 50,
                    stroke: '#000000',
                    strokeWidth: 2,
                    draggable: true
                });
                break;
            case 'heart':
                shape = new Konva.Path({
                    x: x,
                    y: y,
                    data: 'M 0,0 C 0,-20 20,-30 0,-50 C -20,-30 0,-20 0,0 Z',
                    stroke: '#000000',
                    strokeWidth: 2,
                    draggable: true
                });
                break;
            case 'diamond':
                shape = new Konva.RegularPolygon({
                    x: x,
                    y: y,
                    sides: 4,
                    radius: 50,
                    rotation: 45,
                    stroke: '#000000',
                    strokeWidth: 2,
                    draggable: true
                });
                break;
            case 'rightTriangle':
                shape = new Konva.Path({
                    x: x,
                    y: y,
                    data: 'M 0,0 L 100,0 L 0,100 Z',
                    stroke: '#000000',
                    strokeWidth: 2,
                    draggable: true
                });
                break;
            case 'semicircle':
                shape = new Konva.Path({
                    x: x,
                    y: y,
                    data: 'M 0,0 A 50,50 0 0 1 100,0 L 0,0 Z',
                    stroke: '#000000',
                    strokeWidth: 2,
                    draggable: true
                });
                break;
            case 'cross':
                shape = new Konva.Path({
                    x: x,
                    y: y,
                    data: 'M 0,0 L 100,100 M 100,0 L 0,100',
                    stroke: '#000000',
                    strokeWidth: 2,
                    draggable: true
                });
                break;
            default:
                shape = new Konva.Rect({
                    x: x,
                    y: y,
                    width: 100,
                    height: 100,
                    stroke: '#000000',
                    strokeWidth: 2,
                    draggable: true
                });
        }

        if (shape) {
            layer.add(shape);
            layer.draw();
            this.transformer.nodes([shape]);
            layer.draw();
        }
    }

    addImage(url, x, y) {
        if (!this.layers.length) return;

        const layer = this.layers[this.layers.length - 1];
        const imageObj = new Image();
        
        imageObj.onload = () => {
            const image = new Konva.Image({
                x: x,
                y: y,
                image: imageObj,
                width: 100,
                height: 100,
                draggable: true
            });
            
            layer.add(image);
            layer.draw();
            this.transformer.nodes([image]);
            layer.draw();
        };
        
        imageObj.src = url;
    }

    // 设置图层位置
    setLayerPosition(layerIndex, y) {
        if (layerIndex >= 0 && layerIndex < this.layers.length) {
            this.layers[layerIndex].y(y);
            this.stage.draw();
        }
    }

    // 获取当前图层
    getCurrentLayer() {
        return this.currentLayer;
    }

    // 设置当前图层
    setCurrentLayer(layerIndex) {
        if (layerIndex >= 0 && layerIndex < this.layers.length) {
            this.currentLayer = this.layers[layerIndex];
            this.group = this.currentLayer.children[0];
        }
    }
}